<template>
  <div class="home">
    <!-- <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/> -->
    <el-input
      type="textarea"
      :rows="2"
      placeholder="请输入内容"
      v-model="textarea"
    >
    </el-input>
    <el-button type="primary" round @click="search">查找</el-button>
    <el-button @click="exportExcel">导出在线设备</el-button>
    <el-button @click="exportExcel2">导出所有设备</el-button>
    <el-table
      ref="out-excel"
      :data="deviceState"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="index" width="50"> </el-table-column>
      <!-- <el-table-column prop="id" label="id" width="300"> </el-table-column> -->
      <el-table-column prop="facId" label="设备编号" width="300">
      </el-table-column>
      <el-table-column prop="name" label="设备名称" width="300">
      </el-table-column>
      <el-table-column prop="lastOnlineTime" label="上线时间" width="300">
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.stateNum == 0">{{ scope.row.state }}</el-tag>
          <el-tag type="warning" v-if="scope.row.stateNum == 1">{{
            scope.row.state
          }}</el-tag>
          <el-tag type="danger" v-if="scope.row.stateNum == 2">{{
            scope.row.state
          }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      :data="devices"
      style="width: 100%"
      ref="out-excel2"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column prop="id" label="id"> </el-table-column>
      <el-table-column prop="facId" label="设备编号"> </el-table-column>
      <el-table-column prop="name" label="设备名称"> </el-table-column>
      <el-table-column prop="lastOnlineTime" label="上线时间">
      </el-table-column>
      <el-table-column label="是否在线">
        <template slot-scope="scope">
          {{ scope.row.online }}
          <el-switch
            v-model="scope.row.online"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from "@/components/HelloWorld.vue";
import axios from "axios";
import moment from "moment";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "Home",
  data() {
    return {
      devices: [],
      textarea: "",
      deviceState: [],
    };
  },
  methods: {
    async getAllDevices() {
      // let num = 1;
      let pages = 100;
      for (let i = 0; i < pages; i++) {
        let res = await axios.post("/xkh/iotdevice/page_condition", {
          pageNum: i + 1,
          pageSize: 50,
          sortColumns: "id",
          name: "",
          lastOnlineTimeOrder: "DESC",
          facType: "",
        });
        let data = res.data.data;
        pages = data.pages;

        let list = data.list.map((l) => {
          l.bindDataZZ = null;
          l.bindControllerZZ = null;
          l.bindRelayZZ = null;
          // this.devices.push(l);
          return l;
        });
        this.devices.push(...list);
      }
      console.log(this.devices);
    },
    tableRowClassName({ row, rowIndex }) {
      if (!row) {
        console.log("log");
      }
      if (rowIndex % 2 === 1) {
        return "warning-row";
      } else if (rowIndex % 2 === 0) {
        return "success-row";
      }
      return "";
    },
    search() {
      let t = this.textarea.split("\n");
      if (t[t.length - 1].length < 8) t.pop();
      let d = t.map((s) => {
        let t = s.split("#");
        if (t.length <= 1) return;
        return t[1].substring(0, 8);
      });
      d = d.filter((e) => e);
      console.log(d);

      // let result = this.devices.filter((dev) => {
      //   return d.includes(dev.facId);
      // });
      // console.log(result);

      let r = d.map((e) => {
        let msg = {
          id: 0,
          facId: e,
          name: "",
          lastOnlineTime: null,
          state: "未创建",
          stateNum: 2,
        };
        let dev = this.devices.find((r) => r.facId.includes(e));

        if (dev) {
          msg.id = dev.id;
          msg.name = dev.name;
          if (dev.lastOnlineTime) {
            msg.lastOnlineTime = moment(dev.lastOnlineTime).format(
              "yyyy-MM-DD HH:mm:ss"
            );
          }
          msg.state = dev.online ? "在线" : "不在线";
          msg.stateNum = dev.online ? 0 : 1;
        }

        return msg;
      });
      console.log(r);
      this.deviceState.splice(0);
      this.deviceState.push(...r);
    },
    exportExcel() {
      var table = this.$refs["out-excel"].$el;
      var fileName = new Date().toLocaleDateString() + ".xlsx";

      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(table);
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          fileName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    exportExcel2() {
      var table = this.$refs["out-excel2"].$el;
      var fileName = new Date().toLocaleDateString() + ".xlsx";

      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(table);
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          fileName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
  async mounted() {
    // this.http.defaults.withCredentials = false; //设置cross跨域
    // this.http.defaults.headers.common["Access_token"] = token;
    // this.http.defaults.headers.post["Content-Type"] =
    //   "application/json; charset=utf-8";
    // this.http.defaults.headers.post["Accept"] =
    //   "application/json, text/plain, */*";

    setTimeout(() => {
      this.getAllDevices();
    }, 500);
    // this.getAllDevices();
  },
  components: {
    // HelloWorld
  },
};
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
